#include"sqlConnection.h"

//初始化连接池
int initSqlConnectPool(sqlConnectPool *pool, const char *host, const char *user,
		       const char *password, const char *database, int connNum)
{
	printf("Start init sqlpool\n");
	printf("connNum:%d\n", connNum);
	if (connNum <= 0 || connNum > MAX_CONN_NUM) {
		fprintf(stderr, "connNum is out of range\n");
		return -1;
	}
	
	
	printf("初始化锁\n");
	// 初始化锁和条件变量
	if (pthread_mutex_init(&pool->_sqlMutex, NULL) != 0) {
		fprintf(stderr, "Mutex init failed\n");
		return -1;
	}
    printf("初始化条件变量\n");
	pthread_cond_init(&pool->_sqlCond, NULL);

	printf("初始化锁\n");
	// 分配连接数组
	printf("开始分配\n");
	pool->_connections =(sqlConnection *)malloc(sizeof(sqlConnection) * connNum);
	if (pool->_connections == NULL) {
		perror("Failed to allocate memory for connection pool");
		pthread_mutex_destroy(&pool->_sqlMutex);
		pthread_cond_destroy(&pool->_sqlCond);
		return -1;
	}
    printf("分配成功\n");
    

    pool->_connNum = connNum;
    printf("connNum:%d\n", pool->_connNum);
	printf("start init mysql connection\n");
	// 初始化每一个连接
	for (int i = 0; i < connNum; i++) {
		if (mysql_init(&pool->_connections[i]._connect) == NULL) {
			fprintf(stderr,
				"Failed to initialize mysql connection\n");
			return -1;
		}

		if (mysql_real_connect(&pool->_connections[i]._connect, host,user, password, database, 0, NULL,0) == NULL)
        {
			fprintf(stderr, "Failed to connect to MySQL: %s\n",mysql_error(&pool->_connections[i]._connect));
			return -1;
		}

		pool->_connections[i]._useFlag = 0;
		pool->_connections[i]._connsIndex = i;

		printf("Connected to MySQL server: %s\n", host);
	}
	printf("Init sqlpool success\n");
	return 0;
}
//摧毁连接池
void destroySqlConnectPool(sqlConnectPool *pool)
{
	if (pool->_connections) {
		for (int i = 0; i < pool->_connNum; i++) {
			mysql_close(
				&pool->_connections[i]._connect); // 关闭 MySQL 连接
		}
		free(pool->_connections); // 释放连接数组内存
	}

	pthread_mutex_destroy(&pool->_sqlMutex); // 销毁锁
	pthread_cond_destroy(&pool->_sqlCond); // 销毁条件变量
}

//获取一个连接
sqlConnection *getConnection(sqlConnectPool *pool)
{
    pthread_mutex_lock(&pool->_sqlMutex);
    while(1)
    {
	    for (int i = 0; i < pool->_connNum;i++)
        {
            if(pool->_connections[i]._useFlag==0)
            {
                //找到空闲连接
                pool->_connections[i]._useFlag = 1;
                pthread_mutex_unlock(&pool->_sqlMutex);
                return &pool->_connections[i];
            }
        }
        //没有空闲连接，等待
        pthread_cond_wait(&pool->_sqlCond,&pool->_sqlMutex);
    }
}
//释放一个连接
void releaseConnection(sqlConnectPool *pool, sqlConnection *conn)
{
    pthread_mutex_lock(&pool->_sqlMutex);
    conn->_useFlag = 0;
    pthread_cond_broadcast(&pool->_sqlCond);
    pthread_mutex_unlock(&pool->_sqlMutex);
}


//test

// int main()
// {
// 	sqlConnectPool pool;
// 	sqlConnection *conn;

// 	// 初始化连接池
// 	if (initSqlConnectPool(&pool, "localhost", "lunisolar", "4164", "test",
// 			       5) != 0) {
// 		fprintf(stderr, "Failed to initialize connection pool\n");
// 		return 1;
// 	}

// 	// 获取一个连接
// 	conn = getConnection(&pool);
// 	if (conn == NULL) {
// 		fprintf(stderr, "Failed to get a connection\n");
// 		return 1;
// 	}

// 	printf("Connected to database using connection %d\n",
// 	       conn->_connsIndex);

// 	// 执行 SQL 查询
// 	 // 执行 SQL 查询
//     if (mysql_query(&conn->_connect, "SELECT * FROM user")) {
//         fprintf(stderr, "Query failed: %s\n", mysql_error(&conn->_connect));
//     } else {
//         MYSQL_RES *result = mysql_store_result(&conn->_connect);
//         if (result) {
//             printf("Query executed successfully\n");

//             // 打印表头
//             MYSQL_FIELD *fields = mysql_fetch_fields(result);
//             int num_fields = mysql_num_fields(result);
//             for (int i = 0; i < num_fields; i++) {
//                 printf("%s\t", fields[i].name);
//             }
//             printf("\n");

//             // 打印查询结果
//             MYSQL_ROW row;
//             while ((row = mysql_fetch_row(result))) {
//                 for (int i = 0; i < num_fields; i++) {
//                     printf("%s\t", row[i] ? row[i] : "NULL");
//                 }
//                 printf("\n");
//             }

//             mysql_free_result(result);
//         }
//     }

// 	// 释放连接
// 	releaseConnection(&pool,conn);
// 	printf("Connection %d released\n", conn->_connsIndex);

// 	// 销毁连接池
// 	destroySqlConnectPool(&pool);

// 	return 0;
// }